package com.qiaofang.applet.service.other.service.impl;

import com.qiaofang.applet.common.base.MongoBaseService;
import com.qiaofang.applet.common.util.CustomUtil;
import com.qiaofang.applet.service.other.domain.Carousel;
import com.qiaofang.applet.service.other.repository.CarouselRepository;
import com.qiaofang.applet.service.other.service.CarouselService;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.dto.CarouselDetailDto;
import com.qiaofang.applet.service.other.service.dto.CarouselQueryDto;
import com.qiaofang.applet.service.other.service.dto.CarouselResponseDto;
import com.qiaofang.applet.service.other.service.mapstruct.CarouselMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * @author daiyuxiang
 */
@Slf4j
@Service
public class CarouselServiceImpl extends MongoBaseService<Carousel, String> implements CarouselService {

    private final CarouselRepository repository;

    @Autowired
    private CarouselMapper carouselMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    public CarouselServiceImpl(CarouselRepository repository) {
        super(repository);
        this.repository = repository;
    }


    /**
     * 保存轮播图详情（新增、修改、上下架、改排序通用）
     * @param
     */
    @Override
    public void saveDetail(Carousel carousel) {
        String id = carousel.getId();
        if (StringUtils.isEmpty(id)) {
            carousel.setCarouselType(StringUtils.defaultString(carousel.getCarouselType(), "移动端"));
            repository.insert(carousel);
        } else {
            updateById(carousel);
        }
    }

    /**
     * 轮播图列表分页查询
     * @param carouselQueryDto
     * @param pageable
     * @return
     */
    @Override
    public Page<CarouselDetailDto> listDetail(CarouselQueryDto carouselQueryDto, Pageable pageable) {
        String cityCode = carouselQueryDto.getCityCode();
        Query query = new Query();
        query.addCriteria(Criteria.where("corporationCode").is(carouselQueryDto.getCorporationCode()));
        if (StringUtils.isNotEmpty(cityCode)) {
            query.addCriteria(Criteria.where("cityCodes").elemMatch(Criteria.where("$eq").is(cityCode)));
        } else if(!CollectionUtils.isEmpty(carouselQueryDto.getCityCodes())){
            query.addCriteria(Criteria.where("cityCodes").in(carouselQueryDto.getCityCodes()));
        }
        if (StringUtils.isNotBlank(carouselQueryDto.getCarouselStatus())){
            query.addCriteria(Criteria.where("carouselStatus").is(carouselQueryDto.getCarouselStatus()));
        }
        if (StringUtils.isNotBlank(carouselQueryDto.getCarouselType())){
            query.addCriteria(Criteria.where("carouselType").is(carouselQueryDto.getCarouselType()));
        }
        long count = mongoTemplate.count(query.with(pageable), Carousel.class);
        List<Carousel> list = new LinkedList<>();
        if (count > 0) {
            list = mongoTemplate.find(query.with(pageable), Carousel.class);
        }

        List<CarouselDetailDto> dtoList = new ArrayList<>(list.size());
        if (list.size() > 0) {
            Map<String, String> cityMap = cityCompanyService.getCityMap(carouselQueryDto.getCorporationCode());
            StringBuilder cityNames;
            for (Carousel carousel : list) {
                cityNames = new StringBuilder();
                CarouselDetailDto carouselDetailDto = carouselMapper.domainToDetailDto(carousel);
                Set<String> cityCodes = carouselDetailDto.getCityCodes();
                if (CollectionUtils.isEmpty(cityCodes)) {
                    continue;
                }
                for (String code : cityCodes) {
                    cityNames.append(StringUtils.defaultString(cityMap.get(code))).append(",");
                }
                int len = cityNames.length();
                carouselDetailDto.setCityNames(len > 0 ? cityNames.substring(0, len - 1) : "");
                dtoList.add(carouselDetailDto);
            }
        }
        return PageableExecutionUtils.getPage(dtoList, pageable, () -> count);
    }

    @Override
    public List<CarouselResponseDto> getList(CarouselQueryDto carouselQueryDto) {
        String cityCode = carouselQueryDto.getCityCode();
        Query query = new Query();
        query.addCriteria(Criteria.where("corporationCode").is(carouselQueryDto.getCorporationCode()));
        if (StringUtils.isNotEmpty(cityCode)) {
            query.addCriteria(Criteria.where("cityCodes").in(cityCode));
        }
        if (StringUtils.isNotBlank(carouselQueryDto.getCarouselStatus())){
            query.addCriteria(Criteria.where("carouselStatus").is(carouselQueryDto.getCarouselStatus()));
        }
        if (StringUtils.isNotBlank(carouselQueryDto.getCarouselType())){
            query.addCriteria(Criteria.where("carouselType").is(carouselQueryDto.getCarouselType()));
        }
        List<Carousel> list = mongoTemplate.find(query, Carousel.class);
        List<CarouselResponseDto> dtoList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list)) {
            Map<String, String> cityMap = cityCompanyService.getCityMap(carouselQueryDto.getCorporationCode());
            StringBuilder cityNames;
            for (Carousel carousel : list) {
                cityNames = new StringBuilder();
                CarouselResponseDto carouselResponseDto = carouselMapper.domainToResponseDto(carousel);
                Set<String> cityCodes = carouselResponseDto.getCityCodes();
                if (CollectionUtils.isEmpty(cityCodes)) {
                    continue;
                }
                for (String code : cityCodes) {
                    cityNames.append(StringUtils.defaultString(cityMap.get(code))).append(",");
                }
                int len = cityNames.length();
                carouselResponseDto.setCityNames(len > 0 ? cityNames.substring(0, len - 1) : "");
                //图片合集
                carouselResponseDto.setPhotoList(CustomUtil.extractImg(carouselResponseDto.getCarouselInfo()));
                dtoList.add(carouselResponseDto);
            }
        }
        return dtoList;
    }

    /**
     * 删除轮播图
     * @param carouselId
     */
    @Override
    public void remove(String carouselId) {
        repository.deleteById(carouselId);
    }
}
